package com.goldcn.Interceptor;

import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.config.SmsConfig;
import com.google.common.primitives.Longs;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/7/13.
 */
public class SystemContext {
    private static final ThreadLocal request = new ThreadLocal();
    private static final ThreadLocal response = new ThreadLocal();

    public static void setRequest(HttpServletRequest _request) {
        request.set(_request);
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest _request = (HttpServletRequest) request.get();
        return _request;
    }

    public static void removeRequest() {
        request.remove();
    }

    public static void setResponse(HttpServletResponse _response) {
        response.set(_response);
    }

    public static HttpServletResponse getResponse() {
        HttpServletResponse _response = (HttpServletResponse) response.get();
        return _response;
    }

    public static void removeResponse() {
        response.remove();
    }

    public static void removeAll() {
        removeRequest();
        removeResponse();
    }

    public static Long getCompanyID() {
        String companyID = null;
        String ver = getRequest().getHeader("ver");
        if (CommonUtils.isNotEmpty(ver) && ver.equals("2.0")) {
            companyID = getRequest().getHeader("companyID");
            System.out.println("get companyID from header. id=" + companyID);
        }else {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(getRequest().getServletContext());
            SmsConfig smsConfig = (SmsConfig) factory.getBean("smsConfig");
            System.out.println("get companyID from default. id=" + smsConfig.getCompanyID());
            companyID = smsConfig.getCompanyID();
        }
        if (CommonUtils.isEmpty(companyID)) {
            throw new ServiceException("获取公司ID失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return Longs.tryParse(companyID);
    }
}
